/*
 * @description:
 * @Author: lal
 * @Date: 2020-05-19 11:30:55
 * @LastEditors: lal
 * @LastEditTime: 2020-08-15 11:25:33
 */

"use strict";

import { app, protocol, globalShortcut, BrowserWindow, session } from "electron";

import path from "path";
const isDevelopment = process.env.NODE_ENV !== "production";

import { createWindow } from "./windows/create-window";

import checkForUpdates from "./update/checkUpdate";

import registeredShortcuts from "./shortcuts/shortcuts";

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
import "./ipc";
import createMenu from "./menus/create";
import createTray from "./native-ui/tray/tray";

import menuConfig from "./menus/config";
// Scheme must be registered before the app is ready
protocol.registerSchemesAsPrivileged([
  { scheme: "app", privileges: { secure: true, standard: true } },
]);
// Quit when all windows are closed.
app.on("window-all-closed", () => {
  // On macOS it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q

  globalShortcut.unregisterAll();

  if (process.platform !== "darwin") {
    app.quit();
  }
});

function init() {
  let mainWindow = createWindow("mainWindow", {
    show: false,
  });
  createWindow(
    "updateWindow",
    {
      show: false,
      width: 530,
      height: 380,
      parent: mainWindow,
      maximizable: false,
      minimizable: false,
      modal: true,
    },
    "update"
  );
  mainWindow.once("ready-to-show", () => {
    mainWindow.show();
  });
  createMenu(menuConfig);
  createTray();
  checkForUpdates();
  registeredShortcuts();
}
app.whenReady().then(async () => {
  init();

  if (isDevelopment) {
    // 安装vue-devtools
    let extensions = session.defaultSession.getAllExtensions();
    if (!extensions.find(extension => extension.name == "Vue.js devtools")) {
      session.defaultSession.loadExtension(path.resolve(__dirname, "./../src/main/vue-devtools"));
    }
  }
  console.log(`${process.env.USERPROFILE}`);

  app.on("activate", function() {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) {
      init();
    }
  });
});

app.on("will-quit", () => {
  globalShortcut.unregisterAll();
});
// Exit cleanly on request from parent process in development mode.
if (isDevelopment) {
  if (process.platform === "win32") {
    process.on("message", data => {
      if (data === "graceful-exit") {
        app.quit();
      }
    });
  } else {
    process.on("SIGTERM", () => {
      app.quit();
    });
  }
}
